﻿using System;
using System.Linq;
using System.Security.Principal;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;

namespace WebAPI.Filters
{
    //在App_Start/FilterConfig中添加
    //授权过滤器
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class PreAuthorizeAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// 验证授权
        /// 1、添加AllowAnonymous特性的，跳过所有授权，包括登陆授权
        /// 2、检验登陆授权
        /// 3、检验功能授权
        /// </summary>
        /// <param name="filterContext"></param>
        // public override void OnAuthorization(AuthorizationContext filterContext)
        // {
        //     // 跳过登陆授权
        //     if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
        //         || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
        //     {
        //         return;
        //     }
        //
        //     // 是否ajax请求
        //     bool isAjax = filterContext.HttpContext.Request.IsAjaxRequest();
        //
        //     // 开始跳转
        //     try
        //     {
        //         // 用户编码为0时，重新登陆
        //         if (UserCode == 0)
        //         {
        //             filterContext.Result = RedirectLogin();
        //
        //             return;
        //         }
        //
        //         // 跳过权限
        //         if (filterContext.ActionDescriptor.IsDefined(typeof(NoAuthorizeAttribute), true)
        //         || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(NoAuthorizeAttribute), true))
        //         {
        //             return;
        //         }
        //
        //         // 这里开始判断权限
        //         string controller = filterContext.RouteData.Values["controller"].ToString();
        //         string action = filterContext.RouteData.Values["action"].ToString();
        //         string area = string.Empty;
        //
        //         if (filterContext.RouteData.DataTokens.ContainsKey("area"))
        //         {
        //             area = filterContext.RouteData.DataTokens["area"].ToString();
        //         }
        //
        //         bool isPermission = true;
        //
        //         // 无权限时，跳转
        //         if (!isPermission)
        //         {
        //             // 跳转
        //             filterContext.Result = RedirectNoPermission(isAjax);
        //
        //             return;
        //         }
        //     }
        //     catch (Exception ex)
        //     {
        //         Logging.Logger.Error(ex);
        //
        //         filterContext.Result = RedirectLogin();
        //     }
        // }

        /// <summary>
        /// 跳转到无权限的提示
        /// </summary>
        /// <param name="isAjax"></param>
        /// <returns></returns>
        public RedirectToRouteResult RedirectNoPermission(bool isAjax)
        {
            RouteValueDictionary routeValue = null;

            if (isAjax)
            {
                routeValue = new RouteValueDictionary(new { action = "AjaxNoPermission", controller = "Permission" });
            }
            else
            {
                routeValue = new RouteValueDictionary(new { action = "NoPermission", controller = "Permission" });
            }

            return new RedirectToRouteResult(routeValue);
        }

        /// <summary>
        /// 跳转到登录页
        /// </summary>
        /// <returns></returns>
        public RedirectToRouteResult RedirectLogin()
        {
            var routeValue = new RouteValueDictionary(
                                new
                                {
                                    action = "Index",
                                    controller = "login",
                                    area = "Fire",
                                    //ReturnUrl = url
                                });

            return new RedirectToRouteResult(routeValue);
        }

        /// <summary>
        /// 解码
        /// </summary>
        public string UrlDeCode(string str)
        {
            return System.Web.HttpUtility.UrlDecode(str, System.Text.Encoding.UTF8);
        }


        /// <summary>
        /// 重写授权检查方法，返回值为true，允许访问，false，禁止访问。注：此返回401
        /// </summary>
        // protected override bool AuthorizeCore(HttpContextBase httpContext)
        // {
        //     httpContext.Response.ContentType = "application/json; charset=UTF-8";
        //     httpContext.Response.Write("{\"flag\": 2, 	\"message\": \"登陆超时,请重新登陆！\" }");
        //
        //     return true;
        //     if (httpContext == null)
        //     {
        //         throw new ArgumentNullException("httpContext");
        //     }
        //
        //     IPrincipal user = httpContext.User;
        //     if (!user.Identity.IsAuthenticated)
        //     {
        //         return false;
        //     }
        //
        //     if (SplitString(Users).Length > 0 && !(SplitString(Users).Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)))
        //     {
        //         return false;
        //     }

            // Role preparation
            // List<string> allowedRolesRaw = new List<string>(SplitString(Roles));
            // string allowedRolesAd = "";
            //
            // // GetRolesActiveDirectoryGroupName(...) loads role names from the database
            // allowedRolesRaw.ForEach(rc => allowedRolesAd += DomainMapper.GetRolesActiveDirectoryGroupName(DomainMapper.GetRoleIdFromAttributeName(rc), true) + ", ");
            //
            // if (SplitString(Roles).Length > 0 && !(SplitString(allowedRolesAd).Any(user.IsInRole)))
            // {
            //     return false;
            // }
            
            
            // Models.Admin.Dt_User user = App_Code.RoleFuns.IsLoginAdmin(SessianHelper.Intence["user"]);
            // ////string user_f = App_Code.RoleFuns.IsLoginUsers();
            // if (user != null)
            // {
            //     if (Tool.QxCheck.CheckAdminQx(user, httpContext.Curr) == false)
            //     {
            //         httpContext.HttpContext.Response.Write("{\"flag\": 2, 	\"message\": \"无权限\" }");
            //         httpContext.Result = new EmptyResult();
            //     }
            // }
            
            //请求参数user为空，禁止访问
            // if (string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["user"]))
            // {
            //     return false;
            // }
            // return true;
        //}
        
        internal static string[] SplitString(string original)
        {
            if (string.IsNullOrEmpty(original))
            {
                return [];
            }

            var split = from piece in original.Split(',')
                let trimmed = piece.Trim()
                where !string.IsNullOrEmpty(trimmed)
                select trimmed;
            return split.ToArray();
        }
    }
}